package com.cango.student.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyInterceptor implements MethodInterceptor {
    private Object target;
    private Transaction transaction;

    public MyInterceptor(Object target, Transaction transaction) {
        super();
        this.target = target;
        this.transaction = transaction;
    }

    /**
     * 产生代理对象
     */
    public Object createProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(this);//回调函数  拦截器
        enhancer.setSuperclass(this.target.getClass());//设置代理对象的父类
        return enhancer.create();
    }

    @Override
    public Object intercept(Object arg0, Method method, Object[] arg2, MethodProxy arg3) throws Throwable {

        // TODO Auto-generated method stub
        if (method.getName().equals("updatePerson")
                || method.getName().equals("savePerson")
                || method.getName().endsWith("deletePerson")) {
            transaction.beginTransaction();
            method.invoke(this.target, arg2);//目标对象的目标方法
            transaction.commit();
            return null;
        } else {
            return method.invoke(this.target, arg2);//目标对象的目标方法
        }

    }

    public static void main(String[] args) {
        PersonDaoImpl target = new PersonDaoImpl();
        Transaction transaction = new Transaction();
        MyInterceptor interceptor = new MyInterceptor(target, transaction);

        PersonDaoImpl proxy = (PersonDaoImpl) interceptor.createProxy();

        proxy.savePerson();
        System.out.println("=============================");
        proxy.deletePerson();
        System.out.println("=============================");
        proxy.updatePerson();
        System.out.println("=============================");
        for(Person person : proxy.getPersons()){
            System.out.println(person.getPnameString());
        }
    }

}
